<template>
  <div class="app-analysis-container">
    <div class="button-container">
      <a-button type="primary" @click="onClickWeekApp">近一周</a-button>
      <a-button type="primary" @click="onClickMouthApp">近一月</a-button>
      <a-range-picker v-model:value="searchTime" :format="'YYYY-MM-DD'"/>
      <a-button type="primary" shape="circle" @click="onClickSearchTime">
        <template #icon>
          <SearchOutlined/>
        </template>
      </a-button>
    </div>
    <div id="appStatistics" class="app-statistics"></div>
  </div>
</template>

<script setup>
import { SearchOutlined } from "@ant-design/icons-vue";
import { onMounted, ref } from "vue";
import {queryAppStatistics} from "@/api/statistics.js";
import * as echarts from "echarts";

const dateForm = ref({
  startDate: '',
  endDate: ''
});
const searchTime = ref();
const dates = ref([]);
const newApps = ref([]);
const totalApps = ref([]);

const formatDateToBeijingISO = (date) => {
  const beijingOffset = 8 * 60; // 北京时间相对于UTC的分钟数
  const utcDate = new Date(date.getTime() + (beijingOffset * 60 * 1000));
  return `${utcDate.toISOString().split('T')[0]}T00:00:00`;
};

const onClickWeekApp = () => {
  const today = new Date();
  const startOfWeek = new Date(today);
  startOfWeek.setDate(today.getDate() - 6); // 向前推7天
  const endOfWeek = today;

  dateForm.value.startDate = formatDateToBeijingISO(startOfWeek);
  dateForm.value.endDate = formatDateToBeijingISO(endOfWeek);
  fetchAppStatistics();
};

const onClickMouthApp = () => {
  const today = new Date();
  const startOfMonth = new Date(today);
  startOfMonth.setDate(today.getDate() - 29); // 向前推30天
  const endOfMonth = today;

  dateForm.value.startDate = formatDateToBeijingISO(startOfMonth);
  dateForm.value.endDate = formatDateToBeijingISO(endOfMonth);
  fetchAppStatistics();
};

const onClickSearchTime = () => {
  if (!searchTime.value ||!searchTime.value[0] ||!searchTime.value[1]) {
    return;
  }
  dateForm.value.startDate = formatDateToBeijingISO(searchTime.value[0].$d);
  dateForm.value.endDate = formatDateToBeijingISO(searchTime.value[1].$d);
  fetchAppStatistics();
};

const fetchAppStatistics = () => {
  queryAppStatistics(dateForm.value)
    .then(res => {
      dates.value = res.data.data.dateList;
      newApps.value = res.data.data.newAppNum;
      totalApps.value = res.data.data.totalAppNum;
      initChart(); // 初始化图表
    })
    .catch(error => {
      console.log(error);
    });
};

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('appStatistics');
  const myChart = echarts.init(chartDom);

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'cross',
        crossStyle: {
          color: '#999'
        }
      }
    },
    legend: {
      data: ['新增应用', '应用总数']
    },
    xAxis: {
      type: 'category',
      data: dates.value, // 使用响应式数据
      axisLabel: {
        rotate: 45
      }
    },
    yAxis: [
      {
        type: 'value',
        name: '新增应用',
        min: 0,
        alignTicks: true
      },
      {
        type: 'value',
        name: '应用总数',
        min: 0,
        alignTicks: true
      }
    ],
    series: [
      {
        name: '新增应用',
        type: 'bar',
        data: newApps.value, // 使用响应式数据
        color: '#ff792f'
      },
      {
        name: '应用总数',
        type: 'line',
        yAxisIndex: 1,
        data: totalApps.value, // 使用响应式数据
        color: '#1f77ff'
      }
    ]
  };

  option && myChart.setOption(option);

  // 监听窗口大小变化，重绘图表
  window.addEventListener('resize', () => {
    myChart.resize();
  });
};

// 组件挂载时默认获取数据
onMounted(() => {
  onClickMouthApp(); // 可以设置为默认显示本月数据
});
</script>

<style scoped>
.app-analysis-container .button-container {
  display: flex;
  justify-content: right;
  gap: 10px;
}

.app-statistics {
  margin-top: 10px;
  width: 100%;
  height: 400px;
}
</style>
